/**
 * Created by zhouli on 18/3/13
 * Email li.zhou@huilianyi.com
 * 新增成本中心项
 */
import React from 'react';
import { connect } from 'react-redux';
import { Button, Form, Input, Col, Row, Switch, Icon, message, Tag, Select, Tooltip, Badge, Popover, DatePicker } from 'antd';
import CCService from 'containers/setting/cost-center/cost-center.service';
import 'styles/setting/cost-center/cost-center-item/new-cost-center-item.scss';
import { LanguageInput } from 'components/index';
import { deepCopy, messages } from 'share/common';
import menuRoute from 'routes/menuRoute';
import Chooser from 'components/chooser';
import { SelectDepOrPerson } from 'components/index';
import { costCenterItemDefault } from 'containers/setting/cost-center/cost-center.model';
import config from 'config';
import moment from 'moment';

const Option = Select.Option;
const FormItem = Form.Item;

class NewCostCenterItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      parentCostCenterItemSelector: {
        title: messages('setting.key1519')/* 选择成本中心项*/,
        url: `${config.baseUrl}/api/cost/center/items/${this.props.params.costCenterOID}/all`,
        searchForm: [
          { type: 'input', id: 'keyword', label: messages('setting.key1520')/* 关键字*/ },
        ],
        columns: [
          {
            title: messages('setting.key284'/* 成本中心项名称*/),
            dataIndex: 'name',
            width: '15%',
            render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
          },
          {
            title: messages('setting.key285'/* 编码*/),
            dataIndex: 'code',
            width: '15%',
            render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
          },
          {
            title: messages('setting.key286'/* 序号*/),
            dataIndex: 'sequenceNumber',
            width: '10%'
          },
          {
            title: messages('setting.key287'/* 经理*/),
            dataIndex: 'managerFullName',
            width: '15%',
            render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
          },
          {
            title: messages('setting.key288'/* 全员可见性*/),
            dataIndex: 'public',
            width: '15%',
            render: enabled => (
              <Badge
                status={enabled ? 'success' : 'error'}
                text={enabled ? messages('common.status.enable') : messages('common.status.disable')} />)
          },
          {
            title: messages('setting.key289'/* 状态*/),
            dataIndex: 'enabled',
            width: '15%',
            render: enabled => (
              <Badge
                status={enabled ? 'success' : 'error'}
                text={enabled ? messages('common.status.enable') : messages('common.status.disable')} />)
          },
        ],
        key: 'id'
      },
      costCenterItemDetail: deepCopy(costCenterItemDefault),
      // 主要部门
      extraMainDep: {
        res: [],
        title: messages('setting.key43'/* 请选择*/),
        depClassName: 'f-right select-dep-close-wrap',
        className: ['f-right select-dep-close-wrap', 'f-right select-dep-close-wrap select-dep-close-wrap-show']
      },
      // 从属部门
      extraSecDep: {
        res: [],
        title: messages('setting.key43'/* 请选择*/),
        depClassName: 'f-right select-dep-close-wrap',
        className: ['f-right select-dep-close-wrap', 'f-right select-dep-close-wrap select-dep-close-wrap-show']
      },
      // 成本中心项：详情
      CostCenterItemDetailPath: menuRoute.getRouteItem('cost-center-item-detail'),
      manageIsNoRequired: true

    };
  }

  componentDidMount() {
    // 经理是否必填，通过fp控制：costcenteritem.manager.nullable===true,代表可以不填，其他代表必须填写
    // 这个字段必须保证公司的fp配置与集团的fp配置一样，不然在公司模式下修改，会有问题：报错经理必填
    this.setState({
      manageIsNoRequired: this.props.profile['costcenteritem.manager.nullable']
    });
    if (this.props.params.itemId !== 'NEW') {
      this.getCostCenterItemDetail();
    }
  }

  // 查看成本中心项详情
  getCostCenterItemDetail() {
    CCService.getCostCenterItemDetail(this.props.params.itemId)
      .then((response) => {
        const data = response.data;
        this.setState({
          costCenterItemDetail: data,
        }, () => {
          this.forGetCustomValues(this.state.costCenterItemDetail);
          this.initMainSecDep(this.state.costCenterItemDetail);
        });
      });
  }

  // 获取成本中心项扩展字段列表
  forGetCustomValues = (costCenterItemDetail) => {
    const data = costCenterItemDetail.customFormValues;
    if (data && data.length && data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        const custom = data[i].dataSource && JSON.parse(data[i].dataSource);
        if (custom.customEnumerationOID) {
          this._getCustomValues(i, custom.customEnumerationOID);
        }
      }
    }
  }
  // 获取自定义值列表
  _getCustomValues = (index, customEnumerationOID) => {
    const costCenterItemDetail = this.state.costCenterItemDetail;
    // 值列表，循环所有expense field，找到值列表，提前获取值列表的所有值，放在数组内
    CCService.getListByCustomEnumerationOID(customEnumerationOID)
      .then((res) => {
        costCenterItemDetail.customFormValues[index].selectList = res.data;
        this.setState({
          costCenterItemDetail,
        });
      });
  };
  // 回显主要部门与从属部门
  initMainSecDep = (data) => {
    const mainDeps = [];
    const secDeps = [];
    if (data.primaryDepartmentId) {
      const mainDep = {
        id: data.primaryDepartmentId,
        name: data.primaryDepartmentName
      };
      mainDeps.push(mainDep);
    }
    if (data.secondaryDepartmentIds && data.secondaryDepartmentIds.length > 0) {
      for (const id in data.secondaryDepartmentNames) {
        const secDep = {
          id,
          name: data.secondaryDepartmentNames[id]
        };
        secDeps.push(secDep);
      }
    }
    this.selectMainDep(mainDeps);
    this.selectSecDep(secDeps);
  }


  // 校验名称长度
  validateNameLengthErr = (name) => {
    if (name === null || name === undefined || name === '') {
      // 请填写名称
      message.warn(messages('setting.key336'/* 请填写名称*/));
      return true;
    }
    if (name && name.length && name.length > 150) {
      // 名称最多输入150个字符
      message.warn(messages('setting.key1521')/* 名称最多输入150个字符*/);
      return true;
    }
  }
  handleSave = (e) => {
    e.preventDefault();
    let costCenterItemDetail = this.state.costCenterItemDetail;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // 这个很重要，设置扩展字段的
        this.setFromToCustomFormValues(values);
        // 名称涉及到多语言，就不用values
        values.name = costCenterItemDetail.name;


        if (values.parentCostCenterItemOID.length && values.parentCostCenterItemOID.length > 0) {
          values.parentCostCenterItemOID = values.parentCostCenterItemOID[0].costCenterItemOID;
        } else {
          values.parentCostCenterItemOID = null;
        }
        costCenterItemDetail = Object.assign(costCenterItemDetail, values, {
          managerOID: values.managerOID[0] ? values.managerOID[0].userOID : null,
        });

        // 1、工会：把工会主席、工会主任、经审委员放到roles里
        // 2、项目：把项目经理、项目高级经理放到roles里
        const union = ['unionChairman', 'unionDirector', 'economicCommittee'].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
        const project = ['projectManager', 'seniorProjectManager'].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
        if (this.props.location.query.type === 'MCD2001') { // 项目
          if (costCenterItemDetail.roles) { // 编辑
            project.map((item) => {
              costCenterItemDetail.roles.map((role, index) => {
                if (Object.keys(role)[0] === item) {
                  costCenterItemDetail.roles[index][item] = costCenterItemDetail[item].length === 0 ? null : costCenterItemDetail[item][0];
                  // delete costCenterItemDetail[item];
                }
              });
            });
          } else { // 新建
            const tempRoles = [];
            project.map((item) => {
              const obj = {};
              obj[item] = costCenterItemDetail[item].length === 0 ? null : costCenterItemDetail[item][0];
              tempRoles.push(obj);
              // delete costCenterItemDetail[item];
            });
            costCenterItemDetail.roles = tempRoles;
          }
        } else if (this.props.location.query.type === 'MCD3001') { // 工会
          if (costCenterItemDetail.roles) { // 编辑
            union.map((item) => {
              costCenterItemDetail.roles.map((role, index) => {
                if (Object.keys(role)[0] === item) {
                  costCenterItemDetail.roles[index][item] = costCenterItemDetail[item].length === 0 ? null : costCenterItemDetail[item][0];
                  // delete costCenterItemDetail[item];
                }
              });
            });
          } else { // 新建
            const tempRoles = [];
            union.map((item) => {
              const obj = {};
              obj[item] = costCenterItemDetail[item].length === 0 ? null : costCenterItemDetail[item][0];
              // delete costCenterItemDetail[item];
              tempRoles.push(obj);
            });
            costCenterItemDetail.roles = tempRoles;
          }
        } else if (this.props.location.query.type === 'MCD1001') { // sap
          costCenterItemDetail.storeOpenDate = costCenterItemDetail.storeOpenDate ? Number(costCenterItemDetail.storeOpenDate.format('x')) : null
        }
        if (costCenterItemDetail.companyNames) { // 暂时隐藏公司字段
          delete costCenterItemDetail.companyNames;
        }

        if (this.validateNameLengthErr(costCenterItemDetail.name)) {
          return;
        }
        if (costCenterItemDetail.id) {
          this.updateCostCenterItem(costCenterItemDetail);
        } else {
          this.createCostCenterItem(costCenterItemDetail);
        }
      }
    });
  };
  createCostCenterItem = (costCenterItem) => {
    this.setState({
      loading: true,
    });
    CCService.createCostCenterItem(this.props.params.id, costCenterItem)
      .then((res) => {
        if (res) {
          this.setState({ loading: false });
          this.detailCostCenterItem(res.data);
          // 直接跳入详情页
          // this.context.router.goBack();
        }
      })
      .catch(() => {
        this.setState({ loading: false });
      });
  }
  // 成本中心项详情
  detailCostCenterItem = (record) => {
    let path = this.state.CostCenterItemDetailPath.url.replace(':id', this.props.params.id);
    path = path.replace(':itemId', record.costCenterItemOID);
    path += `?type=${this.props.location.query.type}`;
    this.context.router.push(path);
  };
  updateCostCenterItem = (costCenterItem) => {
    this.setState({
      loading: true,
    });
    CCService.updateCostCenterItem(costCenterItem)
      .then((response) => {
        if (response) {
          this.setState({ loading: false });
          this.context.router.goBack();
        }
      })
      .catch(() => {
        this.setState({ loading: false });
      });
  }
  // 点击取消，返回
  handleCancel = (e) => {
    e.preventDefault();
    this.context.router.goBack();
  };
  // 名称：自定义值列表项多语言
  i18nNameChange = (name, i18nName) => {
    this.state.costCenterItemDetail.name = name;
    if (name) {
      this.props.form.setFieldsValue({ name });
    }
    if (this.state.costCenterItemDetail.i18n) {
      this.state.costCenterItemDetail.i18n.name = i18nName;
    } else {
      this.state.costCenterItemDetail.i18n = {
        name: i18nName
      };
    }
  }

  handleChange = (val) => {
    if (this.state.loading) {
      this.setState({
        loading: false
      });
    }
  };

  // 渲染已经选择的部门
  renderButtonTitle(titleArr) {
    if (titleArr.length < 1) {
      // 请选择
      return messages('setting.key43'/* 请选择*/);
    }
    const node = [];
    titleArr.map((item, i) => {
      node.push(<Tag key={i}>{item.name}</Tag>);
    });
    return node;
  }

  // 选择了主要部门的回调
  selectMainDep = (res) => {
    this.state.costCenterItemDetail.primaryDepartmentId = res[0] ? res[0].id : '';
    const extraMainDep = this.state.extraMainDep;
    extraMainDep.res = deepCopy(res);
    if (extraMainDep.res.length > 0) {
      extraMainDep.depClassName = extraMainDep.className[1];
    } else {
      extraMainDep.depClassName = extraMainDep.className[0];
    }
    extraMainDep.title = this.renderButtonTitle(extraMainDep.res);
    this.setState({
      extraMainDep,
    });

  };
  // 选择了从属部门的回调
  selectSecDep = (res) => {
    const ids = [];
    res.map((item) => {
      ids.push(item.id);
    });
    this.state.costCenterItemDetail.secondaryDepartmentIds = ids;
    const extraSecDep = this.state.extraSecDep;
    extraSecDep.res = deepCopy(res);
    if (extraSecDep.res.length > 0) {
      extraSecDep.depClassName = extraSecDep.className[1];
    } else {
      extraSecDep.depClassName = extraSecDep.className[0];
    }
    extraSecDep.title = this.renderButtonTitle(extraSecDep.res);
    this.setState({
      extraSecDep,
    });
  };
  onMouseLeaveDepTag = (e) => {
    e.stopPropagation();
  };
  onMouseEnterDepTag = (e) => {
    e.stopPropagation();
  };
  // 清除已经选择的部门：主要部门
  onCloseMainDepTag = (e) => {
    e.stopPropagation();
    this.selectMainDep([]);
  };
  // 清除已经选择的部门：从属部门
  onCloseSecDepTag = (e) => {
    e.stopPropagation();
    this.selectSecDep([]);
  };

  // 渲染扩展字段
  renderExtendFiled = (extendFileds) => {
    if (extendFileds) {
      if (this.props.params.itemId !== 'NEW') {
        const dom = [];
        for (let i = 0; i < extendFileds.length; i++) {
          dom.push(this.renderEditingContentByMessageKey(extendFileds[i]));
        }
        return dom;
      }
      return (<div className="no-show-extend-tips">
        {messages('setting.key338'/* 新增之后，可以进入编辑扩展字段*/)}
      </div>);

    }
    return (<div />);

  }

  handleUserChange = () => {
    if (this.state.loading) {
      this.setState({
        loading: false
      });
    }
  }
  // -----编辑状态---start
  renderEditingContentByMessageKey = (field) => {
    const messageKey = field.messageKey;
    // 只有值列表
    switch (messageKey) {
      case 'cust_list': {
        return field.selectList && this.renderEditingFiled_cust_list(field);
        break;
      }
      case 'input': {
        return this.renderEditingFiled_input(field);
        break;
      }
      case 'user_info': {
        return this.renderEditingFiled_user_info(field);
        break;
      }
    }
  }
  /*
  * 与产品梁文杰，后端陈良钦讨论决定
  * 这个属于特殊的扩展字段，回显的时候就显示后端返回的值（工号）
  * 上传的时候还是显示名字
  * */
  renderEditingFiled_user_info = (field) => {
    const { getFieldDecorator } = this.props.form;
    return (
      <Col span={8} className="cost-center-form-row">
        <FormItem
          key={field.fieldOID}
          label={field.fieldName}
          colon>
          {getFieldDecorator(field.fieldOID, {
            initialValue: field.value ? [
              {
                employeeID: field.value,
                userOID: field.value
              }
            ] : [],
            rules: [
              {
                required: field.required,
                message: messages('common.please.enter')
              }
            ]
          })(
            <Chooser
              single
              placeholder={messages('common.please.select')}
              labelKey="employeeID"
              valueKey="userOID"
              onChange={this.handleUserChange}
              type="user" />
          )}
        </FormItem>
      </Col>
    );
  }
  renderEditingFiled_input = (field) => {
    const { getFieldDecorator } = this.props.form;
    return (
      <Col span={8} className="cost-center-form-row">
        <FormItem
          key={field.fieldOID}
          label={field.fieldName}
          colon>
          {getFieldDecorator(field.fieldOID, {
            initialValue: field.value,
            rules: [
              {
                max: 50,
                message: messages('enterprise-manage.key155'/* 最多输入50个字符*/)
              },
              {
                required: field.required,
                message: messages('common.please.enter')
              }
            ]
          })(
            <Input placeholder={messages('common.please.enter')} />)}
        </FormItem>
      </Col>
    );
  }
  renderEditingFiled_cust_list = (field) => {
    const { getFieldDecorator } = this.props.form;
    // 如果是值列表类型，在返回的数据上，前端多挂了一个customEnumerationList属性，
    // 这个选择列表就从这个属性上拿了
    return (
      <Col span={8} className="cost-center-form-row">
        <FormItem
          key={field.fieldOID}
          label={field.fieldName &&
            field.fieldName.length &&
            field.fieldName.length > 0 ? field.fieldName : <span>&nbsp;</span>}
          colon>
          {getFieldDecorator(field.fieldOID, {
            initialValue: field.value,
            rules: [
              {
                required: field.required,
                message: messages('common.please.enter')
              }
            ]
          })(
            <Select disabled={!this.props.tenantMode}>
              {_renderCustomEnumerationList(field.selectList.values)}
            </Select>
          )
          }
        </FormItem>
      </Col>
    );

    // 渲染值列表
    function _renderCustomEnumerationList(list) {
      const dom = [];
      if (list.length > 0) {
        list.map((item, index) => {
          dom.push(<Option key={index} value={item.value}>{item.messageKey}</Option>);
        });
        return dom;
      }
      return ('');

    }
  }


  // 把表单的值设置到人员信息扩展字段里面去
  setFromToCustomFormValues = (values) => {
    const customFormValues = this.state.costCenterItemDetail.customFormValues;
    if (!customFormValues) {
      return;
    }
    for (const key in values) {
      for (let i = 0; i < customFormValues.length; i++) {
        if (customFormValues[i].fieldOID === key) {
          if (Object.prototype.toString.call(values[key]) === '[object Array]') {
            customFormValues[i].value = values[key][0] ? values[key][0].employeeID : values[key];
          } else {
            customFormValues[i].value = values[key];
          }
        }
      }
    }
  }
  // -----编辑状态---end
  parentCostCenterItemIdChange = (value) => {
  };

  /**
   * 渲染工会主席、工会主任和经审委员字段(只有在成本中心项是工会时会出现)
   */
  renderThreeUnionRoles = (roles) => {
    const { getFieldDecorator } = this.props.form;
    const keyArr = ['unionChairman', 'unionDirector', 'economicCommittee'];
    const domArr = []; // 存放要渲染的dom
    if (roles.length === 0) {
      roles = [null, null, null];
    } else {
      roles = roles.map((role, index) => !role[Object.keys(role)[0]] ? null : role);
    }
    roles.map((role, index) => {
      domArr.push(<Col span={8} style={{ marginTop: index === 2 && '16px' }}>
        <FormItem
          label={messages(`mcd.cost.center.item.${role ? Object.keys(role)[0] : keyArr[index]}`)}
          colon>
          {getFieldDecorator(role ? Object.keys(role)[0] : keyArr[index], {
            initialValue: role ? [
              {
                fullName: role[Object.keys(role)[0]].fullName,
                employeeID: role[Object.keys(role)[0]].employeeID,
                id: role[Object.keys(role)[0]].id
              }
            ] : [],
            rules: [
              {
                required: true,
                message: messages('common.please.enter')
              }
            ]
          })(
            <Chooser
              single
              placeholder={messages('common.please.select')}
              labelKey="fullName"
              valueKey="employeeID"
              onChange={this.handleUserChange}
              type="user" />
          )}
        </FormItem>
      </Col>);
    });
    return domArr;
  }

  /**
   * 渲染项目经理和项目高级经理字段(只有在成本中心项是项目时会出现)
   */
  renderTwoManager = (roles) => {
    const { getFieldDecorator } = this.props.form;
    const keyArr = ['projectManager', 'seniorProjectManager'].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
    const requiredArr = {
      projectManager: false,
      seniorProjectManager: false
    }
    if (roles.length === 0) {
      roles = [null, null];
    } else {
      roles = roles.map((role, index) => !role[Object.keys(role)[0]] ? null : role);
    }
    return (
      roles.map((role, index) =>
        <Col span={8}>
          <FormItem
            label={messages(`mcd.cost.center.item.${role ? Object.keys(role)[0] : keyArr[index]}`)}
            colon>
            {getFieldDecorator(role ? Object.keys(role)[0] : keyArr[index], {
              initialValue: role ? [
                {
                  fullName: role[Object.keys(role)[0]].fullName,
                  employeeID: role[Object.keys(role)[0]].employeeID,
                  id: role[Object.keys(role)[0]].id
                }
              ] : [],
              rules: [
                {
                  required: requiredArr[role ? Object.keys(role)[0] : keyArr[index]],
                  message: messages('common.please.enter')
                }
              ]
            })(
              <Chooser
                single
                placeholder={messages('common.please.select')}
                labelKey="fullName"
                valueKey="employeeID"
                onChange={this.handleUserChange}
                type="user" />
            )}
          </FormItem>
        </Col>
      )
    );
  }

  /**
   * 1、渲染工会主席、工会主任、经审委员
   * 2、渲染项目经理、项目高级经理
   */
  renderRoles = (roles = []) => {
    const union = ['unionChairman', 'unionDirector', 'economicCommittee'].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
    const project = ['projectManager', 'seniorProjectManager'].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
    if (roles.length > 0) { // 编辑
      const keys = roles.reduce((pre, item) => pre.concat(Object.keys(item)), []).sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
      if (keys.join('') === union.join('')) { // 应该渲染工会主席、工会主任、经审委员
        return this.renderThreeUnionRoles(roles);
      } else if (keys.join('') === project.join('')) { // 应该渲染项目经理、项目高级经理
        return this.renderTwoManager(roles);
      }
    } else if (this.props.location.query.type) { // 新增或者编辑页后端返回roles长度为0
      if (this.props.location.query.type === 'MCD3001') { // 工会的新增页，需要渲染工会主席、工会主任、经审委员
        return this.renderThreeUnionRoles([]);
      } else if (this.props.location.query.type === 'MCD2001') { // 项目的新增页，需要渲染项目经理、项目高级经理
        return this.renderTwoManager([]);
      }
    }
  }

  /**
   * 当成本中心项是SAP且为餐厅时，渲染DO、OC、OM三个角色选择人员选择框
   */
  renderRoleChoose = (costCenterItemDetail) => {
    let roles = costCenterItemDetail.roles || [];
    const { getFieldDecorator } = this.props.form;
    const filterArr = ['T', '9']; // 成本中心编码为T开头为临时餐厅，部门编码以9开头为部门，其余为餐厅
    const keyArr = ['DO', 'OC', 'OM'];
    const domArr = [];
    if (roles.length === 0) {
      roles = [null, null, null];
    } else {
      roles = roles.map((role, index) => !role[Object.keys(role)[0]] ? null : role);
    }
    if (this.props.location.query.type) {
      if (this.props.location.query.type === 'MCD1001' && !filterArr.includes(costCenterItemDetail.code[0])) {
        roles.map((role, index) => {
        if(!(role ? Object.keys(role)[0] : keyArr[index])){
          return
        }

          domArr.push(<Col span={8} style={{ marginTop: index === 2 && '16px' }}>
            <FormItem
              label={messages(`mcd.cost.center.item.${role ? Object.keys(role)[0] : keyArr[index]}`)}
              colon>
              {getFieldDecorator(role ? Object.keys(role)[0] : keyArr[index], {
                initialValue: role ? [
                  {
                    fullName: role[Object.keys(role)[0]].fullName,
                    employeeID: role[Object.keys(role)[0]].employeeID,
                    id: role[Object.keys(role)[0]].id
                  }
                ] : [],
                rules: [
                  {
                    required: false,
                    message: messages('common.please.enter')
                  }
                ]
              })(
                <Chooser
                  single
                  placeholder={messages('common.please.select')}
                  labelKey="fullName"
                  valueKey="employeeID"
                  onChange={this.handleUserChange}
                  disabled
                  type="user" />
              )}
            </FormItem>
          </Col>);
        });
      }
    }
    return domArr;
  }

  /**
   * 开店日期限制在1970年到当前
   * @param {moment} currentDate 
   */
  disabledDate = (currentDate) => {
    const minDate = moment('1970-01-01')
    const maxDate = moment()
    return currentDate && !(currentDate.isSameOrAfter(minDate) && currentDate.isSameOrBefore(maxDate))
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const {
      loading, costCenterItemDetail, extraMainDep, extraSecDep, parentCostCenterItemSelector, manageIsNoRequired,
    } = this.state;
    const { tenantMode, params } = this.props;
    let depClass = 'select-dep-search-area';
    if (!tenantMode) {
      depClass = 'select-dep-search-area select-dep-search-area-disabled';
    }
    return (
      <div className="new-cost-center-item">
        <Form onSubmit={this.handleSave} onChange={this.handleChange}>
          <Row gutter={24} className="cost-center-form-row">
            <Col span={8}>
              <FormItem
                label={messages('setting.key339'/* 成本中心项代码*/)}
                colon>
                {getFieldDecorator('code', {
                  initialValue: costCenterItemDetail.code,
                  rules: [
                    {
                      required: true,
                      message: messages('common.please.enter')
                    },
                    {
                      message: messages('setting.key340'/* 最多36个字符，只支持字母与数字和一些限定特殊字符*/),
                      validator: (rule, value, cb) => {
                        if (value === null || value === undefined || value === '') {
                          cb();
                          return;
                        }
                        const regExp = /^[a-z0-9_ ]+$/i;
                        // 去掉空格
                        value = value.replace(/ /g, '');
                        if (value.length <= 36) {
                          cb();
                        } else {
                          cb(false);
                        }
                      },
                    },
                  ]
                })(
                  <Input
                    disabled={(costCenterItemDetail.id && costCenterItemDetail.code) || !this.props.tenantMode}
                    placeholder={messages('common.please.enter')} />)
                }
              </FormItem>
              <div className="cost-center-code-tips">
                {messages('setting.key341'/* 成本中心项代码保存后将不可修改*/)}
              </div>
            </Col>
            <Col span={8}>
              <FormItem label={messages('setting.key342'/* 成本中心项名称*/)}>
                {getFieldDecorator('name', {
                  initialValue: costCenterItemDetail.name,
                  rules: [
                    {
                      required: true,
                      message: messages('common.please.enter')
                    },
                    {
                      max: 150,
                      message: messages('setting.key1522')/* 最多输入150个字符*/,
                    }],
                })(
                  <div>
                    <LanguageInput
                      disabled={!tenantMode}
                      key={1}
                      name={costCenterItemDetail.name}
                      i18nName={costCenterItemDetail.i18n ? costCenterItemDetail.i18n.name : ''}
                      isEdit={costCenterItemDetail.id}
                      nameChange={this.i18nNameChange}
                    />
                  </div>
                )}
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem
                label={messages('setting.key344'/* 序号*/)}
                colon>
                {getFieldDecorator('sequenceNumber', {
                  initialValue: costCenterItemDetail.sequenceNumber,
                  rules: [
                    {
                      message: messages('setting.key1448'/* 请输入正整数*/),
                      validator: (rule, value, cb) => {
                        if (value === null || value === undefined || value === '') {
                          cb();
                          return;
                        }
                        // 去掉空格
                        value = value.replace(/ /g, '');
                        if (value.split('.').length > 1) {
                          cb(false);
                        } else {
                          cb();
                        }
                      },
                    },
                  ]
                })(
                  <Input
                    disabled={!tenantMode}
                    placeholder={messages('common.please.enter')} />)
                }
              </FormItem>
              <div className="cost-center-index-tip">
                {messages('setting.key1663')/* 按照序号由小到大排序，不填默认为999。序号之间尽量保持一定的步长，便于后续调整，如首位10，间隔10。*/}
              </div>
            </Col>
          </Row>
          <Row gutter={24} className="cost-center-form-row">
            <Col span={8}>
              <div className="main-select-dep-wrap">
                <div className="select-dep-search-area-title">
                  {messages('setting.key347'/* 主要部门:(单选)*/)}
                </div>
                <div className={depClass}>
                  <div className="f-left select-dep-wrap">
                    <SelectDepOrPerson
                      buttonDisabled={!tenantMode}
                      renderButton={false}
                      multiple={false}
                      title={extraMainDep.title}
                      onlyDep
                      onConfirm={this.selectMainDep} />
                  </div>
                  <div
                    className={extraMainDep.depClassName}
                    onMouseLeave={this.onMouseLeaveDepTag}
                    onMouseEnter={this.onMouseEnterDepTag}
                    onClick={this.onCloseMainDepTag}>
                    <Icon type="close-circle" className="closeCircle" />
                  </div>
                </div>
              </div>
            </Col>
            <Col span={8}>
              <div className="sec-select-dep-wrap">
                <div className="select-dep-search-area-title">
                  {messages('setting.key348'/* 从属部门:(可多选)*/)}
                </div>
                <div className={depClass}>
                  <div className="f-left select-dep-wrap">
                    <SelectDepOrPerson
                      buttonDisabled={!tenantMode}
                      renderButton={false}
                      title={extraSecDep.title}
                      onlyDep
                      onConfirm={this.selectSecDep} />
                  </div>
                  <div
                    className={extraSecDep.depClassName}
                    onMouseLeave={this.onMouseLeaveDepTag}
                    onMouseEnter={this.onMouseEnterDepTag}
                    onClick={this.onCloseSecDepTag}>
                    <Icon type="close-circle" className="closeCircle" />
                  </div>
                </div>
              </div>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('setting.key349'/* 经理*/)}
                colon>
                {getFieldDecorator('managerOID', {
                  initialValue: costCenterItemDetail.managerFullName ? [
                    {
                      fullName: costCenterItemDetail.managerFullName,
                      userOID: costCenterItemDetail.managerOID
                    }
                  ] : [],
                  rules: [
                    {
                      required: !manageIsNoRequired,
                      message: messages('common.please.enter')
                    },
                  ]
                })(
                  <Chooser
                    single
                    disabled={!tenantMode}
                    placeholder={messages('common.please.select')}
                    labelKey="fullName"
                    valueKey="userOID"
                    onChange={this.handleChange}
                    type="user" />
                )
                }
              </FormItem>
            </Col>
          </Row>
          <Row gutter={24} className="cost-center-form-row">
            <Col span={8}>
              <FormItem
                label={messages('setting.key1517')/* 父级成本中心项*/}
                colon>
                {getFieldDecorator('parentCostCenterItemOID', {
                  initialValue: costCenterItemDetail.parentCostCenterItemOID ? [{
                    costCenterItemOID: costCenterItemDetail.parentCostCenterItemOID,
                    name: costCenterItemDetail.parentCostCenterItemName
                  }] : [],
                })(
                  // todo
                  // 后端会返回一个父级成本中心 id或者oid，这边选择父级成本中心下面的项
                  // 后端会单独提供一个根据成本中心 id或者oid 查询成本中心项的接口
                  <Chooser
                    single
                    disabled={`${params.costCenterOID}` === 'null' ||
                      `${params.costCenterOID}` === 'undefined'}
                    selectorItem={parentCostCenterItemSelector}
                    placeholder={messages('common.please.select')}
                    labelKey="name"
                    valueKey="costCenterItemOID"
                    onChange={this.parentCostCenterItemIdChange}
                    listExtraParams={{
                      parentCostCenterId: costCenterItemDetail.parentCostCenterId,
                      enable: true
                    }} />
                )
                }
              </FormItem>
            </Col>
            {this.renderRoleChoose(costCenterItemDetail)}
            {this.renderRoles(costCenterItemDetail.roles)}
            {
              // 2020-11-19 sap成本中心项增加：isDepart(属性)、storeOpenDate(开店日期)
              this.props.location.query.type && this.props.location.query.type === 'MCD1001' ? <Col span={8} style={{ marginTop: '16px' }}>
                <FormItem
                  label={'属性'}
                >
                  {getFieldDecorator('isDepart', {
                    initialValue: costCenterItemDetail.isDepart
                  })(
                    <Select placeholder={'请选择'}>
                      <Option value={1}>部门</Option>
                      <Option value={2}>餐厅</Option>
                      <Option value={3}>临时餐厅</Option>
                    </Select>
                  )}
                </FormItem>
              </Col> : null
            }
            {
              // 2020-11-19 sap成本中心项增加：isDepart(属性)、storeOpenDate(开店日期)
              this.props.location.query.type && this.props.location.query.type === 'MCD1001' ? <Col span={8} style={{ marginTop: '16px' }}>
                <FormItem
                  label={'开店日期'}
                >
                  {getFieldDecorator('storeOpenDate', {
                    initialValue: costCenterItemDetail.storeOpenDate ? moment(costCenterItemDetail.storeOpenDate) : null
                  })(
                    <DatePicker
                      disabledDate={(currentDate) => this.disabledDate(currentDate)}
                      style={{ width: '100%' }}
                      format='YYYY-MM-DD'
                    />
                  )}
                </FormItem>
              </Col> : null
            }
            {/* {
              ['MCD2001', 'MCD3001'].includes(this.props.location.query.type) ? <Col span={8} style={{ marginTop: '16px' }} >
                <FormItem
                  label={this.props.location.query.type === 'MCD3001' ? messages('mcd.cost.center.item.unionCompanyNames') : messages('mcd.cost.center.item.projectCompanyNames')}
                  colon>
                  {getFieldDecorator('companyNames', {
                    initialValue: costCenterItemDetail.companyNames ? costCenterItemDetail.companyNames : [],
                    rules: [
                      {
                        required: true,
                        message: messages('common.please.enter')
                      }
                    ]
                  })(
                    <Chooser
                      single={this.props.location.query.type === 'MCD2001'}
                      placeholder={messages('common.please.select')}
                      labelKey="name"
                      valueKey="companyCode"
                      // valueKey="id"
                      onChange={this.handleUserChange}
                      type="available_company" />
                  )}
                </FormItem>
              </Col> : null
            } */}

          </Row>

          <Row gutter={24} className="cost-center-form-row">
            <Col span={8}>
              <FormItem
                label={messages('setting.key1649')/* 适用全部公司*/}
                colon={false}>
                {getFieldDecorator('allTenant', {
                  initialValue: costCenterItemDetail.allTenant,
                  valuePropName: 'checked',
                  rules: [],
                })(<Switch
                  disabled={!tenantMode}
                  checkedChildren={<Icon type="check" />}
                  unCheckedChildren={<Icon type="cross" />} />)
                }
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem
                label={messages('setting.key350'/* 全员可见*/)}
                colon={false}>
                {getFieldDecorator('public', {
                  initialValue: costCenterItemDetail.public,
                  valuePropName: 'checked',
                  rules: [],
                })(<Switch
                  disabled={!tenantMode}
                  checkedChildren={<Icon type="check" />}
                  unCheckedChildren={<Icon type="cross" />} />)
                }
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem
                label={messages('common.status', { status: '' })}
                colon>
                {getFieldDecorator('enabled', {
                  initialValue: costCenterItemDetail.enabled,
                  valuePropName: 'checked',
                  rules: [],
                })(<Switch
                  disabled={!tenantMode}
                  checkedChildren={<Icon type="check" />}
                  unCheckedChildren={<Icon type="cross" />} />)
                }
              </FormItem>
            </Col>
          </Row>

          <div className="basic-info-extend-title">
            {messages('setting.key351'/* 成本中心项扩展字段*/)}
            &nbsp;&nbsp;
            <Tooltip title={messages('setting.key352'/* 可以在成本中心--成本中心项扩展字段进行编辑成本中心项扩展字段*/)}>
              <Icon type="question-circle" />
            </Tooltip>
          </div>
          <Row gutter={24}>
            {this.renderExtendFiled(costCenterItemDetail.customFormValues)}
          </Row>
          <Button type="primary" loading={loading} htmlType="submit">
            {messages('common.save') /* 保存*/}
          </Button>
          <Button onClick={this.handleCancel} style={{ marginLeft: 8 }}>
            {messages('common.cancel') /* 取消*/}
          </Button>
        </Form>
      </div>
    );
  }
}

NewCostCenterItem.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    tenantMode: state.main.tenantMode,
  };
}

const WrappedNewCostCenterItem = Form.create()(NewCostCenterItem);

export default connect(mapStateToProps)(WrappedNewCostCenterItem);
